×
☰ See All Chapters

JavaScript ES6 class Constructor

Constructor is a special block which is used to initialize an object. Objects of class can be created by invoking constructor or without invoking constructor objects cannot be created.  Constructor must be named constructor.

class Box {

    constructor() {

    }

}

Constructors can have parameters:

class Point {

        width;

        length;

        constructor(width, length) {

           this.width = width;

           this.length = length;

        }

}

Constructor overloading is not allowed. If no constructor is defined in code, a constructor with no arguments (a no-arg constructor) will be considered.

javascript-es6-class-constructor-0
 

Each class can have only one constructor. When creating objects of any class, consturcor should be invoked and while calling constaructor arguements should be passed if constaructor has parameters. Constructor can be invoked only with the help of “new” keyword and can never be accessed with the help of dot (“.”) operator or it can never be invoked by an object. Constructor is always executed only once during the creation of every new object. Constructors are not inherited into sub class (sub class will be studied in later chapters).

 


All Chapters
Author